package com.kungfu.utils;

import com.google.gson.Gson;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class XmlConvertEntityUtils {
    public static String readStringXml(String xml) {
        xml = xml.replace("&nbsp;", " ");
        Document doc = null;
        Map<String, String> result = new HashMap<>();

        try {
            // 下面的是通过解析xml字符串的
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML
            Element rootElt = doc.getRootElement(); // 获取根节点
            System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称
            Iterator iter = rootElt.elementIterator("Item"); // 获取根节点下的子节点head
            // 遍历Item节点
            while (iter.hasNext()) {
                Element recordEle = (Element) iter.next();
                if (!StringUtils.isEmpty(recordEle.attributeValue("Value"))) {
                    result.put(recordEle.attributeValue("Key"), recordEle.attributeValue("Value"));
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Gson().toJson(result);
    }
}
